import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_app/bean/list_problem_collect_entity.dart';
import 'package:flutter_app/r.dart';
import 'package:flutter_app/utils/EventBusUtils.dart';
import 'package:flutter_app/values/MyColors.dart';
import 'package:flutter_app/ui/collect/CollectListModel.dart';
import 'package:flutter_app/widget/empty_view.dart';
import 'package:flutter_screenutil/src/size_extension.dart';
import 'package:get/get.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import 'collect_detail2/collect_detail_view.dart';


/**
 * @Description: 采集列表
 * @Author: 下雨了
 * @CreateDate: 2021-10-26 13:39
 * @UpdateUser: 更新者
 * @UpdateDate:  2021-10-26 13:39
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
///
class CollectListPage extends StatefulWidget {
  final String title;
  final String page;

  CollectListPage({Key? key, required this.title, required this.page}) : super(key: key);

  @override
  _CollectListPageState createState() {
    return _CollectListPageState();
  }
}

class _CollectListPageState extends State<CollectListPage> with AutomaticKeepAliveClientMixin {
  // initialRefresh 是否最初刷新
  late RefreshController _refreshController = new RefreshController(initialRefresh: false);
  
  late CollectListModel _collectListMode;
  ListProblemCollectEntity? _listProblemCollectEntity;
  
  late int currentPage = 1;

  /// 订阅事件 CollectDetailEvent
  late StreamSubscription<CollectDetailEvent> _collectDetailEvent;

  /// 刷新
  void _onRefresh() async {
    currentPage = 1;
    // 监视网络获取
    await Future.delayed(Duration(milliseconds: 1000));
    // 如果失败,使用refreshFailed ()
    _collectListMode.postListProblemCollect(currentPage, widget.page).then((value) {
      _refreshController.refreshCompleted();
      _refreshController.resetNoData();
    });
  }

  /// 加载
  void _onLoading() async {
    // 监视网络获取
    await Future.delayed(Duration(milliseconds: 1000));
    // 如果完成使用loadFailed()，如果没有数据返回，使用LoadNoData()
    if (mounted) setState(() {});
    int? totalPages = _collectListMode.listProblemCollectEntity!.totalPages;
    if (currentPage < totalPages!) {
      currentPage++;
      _collectListMode.postListProblemCollect(currentPage, widget.page).then((value) => _refreshController.loadComplete());
    } else {
      _refreshController.loadNoData();
    }
  }

  @override
  void initState() {
    super.initState();
    _collectListMode = context.read<CollectListModel>();
    _collectListMode.postListProblemCollect(currentPage, widget.page);

    /// 订阅事件 HomeEvent 处理
    _collectDetailEvent = bus.listen((event) {
      _collectListMode.upProblemCollectData(event.groupId, event.taskStatus, event.memberStatus, event.totalProblem);
    });
  }

  @override
  void dispose() {
    super.dispose();
    _collectDetailEvent.cancel();
  }

  @override
  Widget build(BuildContext context) {
    _listProblemCollectEntity = context.watch<CollectListModel>().listProblemCollectEntity;
    super.build(context);
    return SmartRefresher(
      controller: _refreshController,
      //  允许下拉刷新
      enablePullDown: true,
      // 允许上拉加载
      enablePullUp: true,
      // 刷新
      onRefresh: _onRefresh,
      // 加载
      onLoading: _onLoading,
      header: WaterDropHeader(complete: Text('刷新完成', style: TextStyle(color: MyColors.FF333333))),
      footer: ClassicFooter(loadingText: '加载中...', idleText: '上拉加载更多..', noDataText: '没有更多数据了'),
      child: (_listProblemCollectEntity?.content?.length ?? 0) > 0 ? ListView.builder(
        itemCount: _listProblemCollectEntity?.content!.length,
        physics: BouncingScrollPhysics(),
        itemBuilder: (BuildContext context, int index){
          return GestureDetector(
            child: _CollectListItem(_listProblemCollectEntity!.content![index]),
            onTap: (){
              
            },
          );
        },
      ) : EmptyView(),
    );
  }

  Widget _CollectListItem(ListProblemCollectContent item) {
    return Container(
        height: 115.r,
        child: Card(
          margin: EdgeInsets.fromLTRB(16.r, 5.r, 16.r, 5.r),
          child: Stack(
            children: [
              Visibility(
                visible: item.taskStatus=='1',
                child: Align(
                  alignment: Alignment.bottomRight,
                  child: Container(
                    margin: EdgeInsets.only(right: 20.5.r, bottom: 12.5.r),
                    child: Visibility(
                      visible: item.grade != "",
                      child: Image.asset(
                        item.grade == "1" ? R.assetsImgIcon35
                            : item.grade == "2" ? R.assetsImgIcon18
                            : item.grade == "3" ? R.assetsImgIcon37
                            : R.assetsImgIcon16, width: 55.5.r,),
                    ),
                  ),
                ),
              ),
              Container(
                padding: EdgeInsets.fromLTRB(15.5.r, 11.r, 15.5.r, 12.5.r),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  // mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    Expanded(
                      child: RichText(
                        text: TextSpan(
                          children: [
                            WidgetSpan(child: Image.asset(item.taskStatus =="0" ? R.assetsImgIcon17 : R.assetsImgIcon34, height: 18.r,)  ),
                            TextSpan(
                              text: "  " + item.taskTitle!, style: TextStyle(color: Colors.black, fontSize: 15.sp, fontWeight: FontWeight.w600),)
                          ]
                        ),
                        maxLines: 2,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                    Container(
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Row(
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: [
                              Container(margin: EdgeInsets.only(top: 2.r),child: Image.asset(R.assetsImgIcon22, width: 9.r,)),
                              SizedBox(width: 5.5.r,),
                              item.totalProblem == "0" ?
                                Text("暂未上报问题", style: TextStyle(color: MyColors.FF666666, fontSize: 12.sp))  :
                                Row(
                                  crossAxisAlignment: CrossAxisAlignment.end,
                                  children: [
                                    Text("已上报", style: TextStyle(color: MyColors.FF666666, fontSize: 12.sp)),
                                    Text(item.totalProblem!, style: TextStyle(color: MyColors.FF2763B9, fontSize: 12.sp, fontWeight: FontWeight.w600)),
                                    Text("条问题", style: TextStyle(color: MyColors.FF666666, fontSize: 12.sp)),
                                  ],
                                ),
                            ],
                          ),
                          Visibility(
                            visible: item.taskStatus == "0",
                            child: SizedBox(
                              width: 85.r,
                              height: 30.r,
                              child: TextButton(
                                style: ButtonStyle(
                                  padding: MaterialStateProperty.all(EdgeInsets.all(0)),
                                  backgroundColor: MaterialStateProperty.all<Color>(MyColors.FF2763B9),
                                  shape:  MaterialStateProperty.all(
                                    RoundedRectangleBorder(
                                      borderRadius: BorderRadius.all(Radius.circular(2)),
                                    ),
                                  ),
                                ),
                                // memberRole 0组员 1组长 totalProblem上报问题数量
                                child: Text(_getButtonText(item.memberRole!, item.memberStatus!, item.totalProblem!), style: TextStyle(
                                    color: MyColors.FFFFFFFF, fontSize: 14.sp,),),
                                onPressed: () {
                                  Get.to(() => CollectDetailPage(title: "任务详情",), arguments: item.groupId);
                                },
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              )
            ],
          ),
        ),
    );
  }

  // memberRole 0组员 1组长
  // memberStatus 自身状态0未上传1待确认2已确认
  // totalProblem 上报问题数量
  String _getButtonText(String memberRole, String memberStatus, String totalProblem) {
    String str;
    if (memberRole == "1") {
      switch (memberStatus) {
        case "0":
          str = "完成填报";
          break;
        case "2":
          str = "已确认问题";
          break;
        default:
          str = "";
          break;
      }
    } else {
      switch (memberStatus) {
        case "0":
          str = "待完成填报";
          break;
        case "1":
          str = "确认问题";
          break;
        default:
          str = "已确认问题";
          break;
      }
    }
    return str;
  }

  @override
  bool get wantKeepAlive => true;
}
